#include <my_header.h>
#include <string.h>

/* Usage: 
 * 递归遍历目录，统计目录数与文件数
 * 编译成功的测试命令 ./01_Dir_Recurse ../../..
 * */

static int dirs = 0;
static int files = 0;

// 深度优先搜索打印目录树
void DFS_print(char* path, int width){
    // 打开文件，检查错误
    DIR* dirp = opendir(path);
    if(dirp == NULL){
        return;
    }

    struct dirent* pdirent;
    while(1){
        pdirent = readdir(dirp);
        if(pdirent == NULL){
            break;
        }
        if(strcmp(pdirent->d_name, ".") == 0 || 
           strcmp(pdirent->d_name, "..") == 0){
            continue;
        }
        
        for(int i = 0; i < width * 4; i++){
            printf(" ");
        }
        printf("%s\n", pdirent->d_name);
        if(pdirent->d_type == DT_DIR){
            dirs++;
           // Avoid using sprintf as it may cause buffer overlap when rewriting 'path'
            char next_path[1024];
            memset(next_path, 0, sizeof(next_path));
            snprintf(next_path, sizeof(next_path), "%s/%s", path, pdirent->d_name);
            DFS_print(next_path, width + 1);
        }
        else{
            files++;
        }
    }

    closedir(dirp);
}

int main(int argc, char *argv[]){                                  
    ARGS_CHECK(argc, 2);
    
    // 打印根目录名称
    printf("%s \n", argv[1]);
    
    // 从根目录开始先序遍历
    char path[1024] = {0};
    strcpy(path , argv[1]);
    int width = 1;
    DFS_print(path, width);
    printf("\n%d directories, %d files", dirs, files);

    return 0;
}

